# coding=utf-8
"""
    @project: 15python_spider
    @Author：frank
    @file： 03_baidu_translate.py
    @date：2024/3/4 21:49
"""
import re

import execjs
import requests


class BaiduTranslateSpider(object):
    def __init__(self):
        self.get_url = 'https://fanyi.baidu.com/?aldtype=16047'
        self.headers = {
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-User': '?1',
            'Sec-Fetch-Dest': 'document',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cookie': 'BIDUPSID=363E1FC76FDF32695308C6F0FE6DB553; PSTM=1684071850; BAIDUID=967747A36176376BC0C561D74F0DB267:FG=1; BAIDUID_BFESS=967747A36176376BC0C561D74F0DB267:FG=1; ZFY=0PJD:A3zA:BDkk:AVDxwXqBl6:AZOZunhTaOsPAnSTNfUes:C; H_PS_PSSID=40008_39661_40207_40216_40223_40294_40290_40289_40285_40318_40080; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BDRCVFR[Px0Hc1hvWQb]=mk3SLVN4HKm; BA_HECTOR=042g2100250k8ha58k84ah806gapsc1iubd9d1s; BDRCVFR[S4-dAuiWMmn]=k4cOsjTQtLnfj63njb1nWRkg1DkPNqC; PSINO=5; APPGUIDE_10_6_9=1; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1709560632; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1709560632; ab_sr=1.0.1_YTUxODA4MjMxZmI0NWM1MTJhYjY1Njk3MWZiOWMyODg0NjMzYjMxZDFiMDdmNTA1NjI4MWY4MmE1MDBlNmUwZDY2MGEyYjUzMGNmNDAwM2M1M2UxYTA3MTkzNWQ0Y2ZjMDdiOTI1NGY5ZTkxMmJkNzc2NjMwYTdmNDUxN2JiYjQ1MmU1NjE4YzZkYjBhMzYwZmU4ZDFjZjZiMWQxNDdjOTMyODAwNDY5ZDMzYjdkYzExNDUxN2YxZWMyODk0NmMzNjkyMjczMzNlMjdlMjY0NDhhYmM3NTQ3NjUwNGQ0ZGM='

        }

    # 获取token
    def get_token(self):
        html = requests.get(url=self.get_url, headers=self.headers).text
        # 正则解析
        pattern = re.compile("token: '(.*?)'", re.S)
        token = pattern.findall(html)[0]
        return token

    # 获取sign
    def get_sign(self, word):
        with open('node.js', 'r') as f:
            js_data = f.read()
            execjs_obj = execjs.compile(js_data)
            sign = execjs_obj.eval('get_sign("{}")'.format(word))
            return sign
    # 获取翻译结果
    def get_result(self, word):
        token = self.get_token()
        sign = self.get_sign(word)
        # 把formdata 定义成字典
        formdata = {
            'from': 'en',
            'to': 'zh',
            'query': word,
            'transtype': 'realtime',
            'simple_means_flag': '3',
            'sign': sign,
            'token': token,
            'domain': 'common',
         }
        html_json = requests.post(
            url='https://fanyi.baidu.com/v2transapi?from=en&to=zh',
            data = formdata,
            headers=self.headers
                                  ).json()

        return html_json


if __name__ == '__main__':
    spider = BaiduTranslateSpider()
    # token = spider.get_token()
    # print(token)
    # sign = spider.get_sign('hello')
    # print(sign)
    while True:
        word = input('请输入要翻译的单词(输入数字结束程序):')
        if word.isnumeric():
            print('程序结束!')
            break
        result = spider.get_result(word)
        print(result)
